package delivery

import (
	"log"
	"strings"
	"time"
	"xiehui-service/app/common/request"
	"xiehui-service/app/common/response"
	"xiehui-service/app/services/erp_services"
	"xiehui-service/app/services/types"
	"xiehui-service/global"

	"github.com/gin-gonic/gin"
	"go.uber.org/zap"
)

// 冗余的天数
const moreDay = -1

// 查询发货单小票
func DeliveryList(c *gin.Context) {
	var form request.DeliveryList
	if err := c.ShouldBindJSON(&form); err != nil {
		response.ValidateFail(c, request.GetErrorMsg(form, err))
		return
	}
	if form.PageNum == 0 {
		form.PageNum = 1
	}
	if form.PageSize == 0 {
		form.PageSize = 1000
	}

	// 计算时间，冗余1天的发货单
	queryTime, err := time.Parse(time.DateTime, form.Lasttime)
	if err != nil {
		response.BusinessFail(c, err.Error())
		return
	}

	// orderDelivery, err := services.OrderDeliveryService.OrderListByLasttime(queryTime.Add(moreDay*24*time.Hour).Format(time.DateTime), types.Pagination{PageNum: form.PageNum, PageSize: form.PageSize})
	orderProduction, err := erp_services.OrderProductionService.GetListByLasttime(queryTime.Add(moreDay*24*time.Hour).Format(time.DateTime), global.App.Config.App.CompanyId, "1", types.Pagination{PageNum: form.PageNum, PageSize: form.PageSize})
	if err != nil {
		response.BusinessFail(c, err.Error())
		return
	}

	// 获取产线的配比
	mixer := erp_services.OrderTaskService.GetMixer(global.App.Config.App.CompanyId)
	mixerSlice := strings.Split(mixer, ",")
	var productionSlice []interface{}
	for _, production := range orderProduction.List {
		consumptionDetail, err := erp_services.OrderConsumptionService.GetByProductionId(int64(production.ID.ID), global.App.Config.App.CompanyId)
		if err != nil {
			log.Println("查询生产单耗料失败", err)
			global.App.Log.Info("查询生产单耗料异常:", zap.Any("查询生产单耗料失败:", err))
			continue
		}

		dList := make(map[string]interface{})
		mList := make(map[string]interface{})
		for _, mixerItem := range mixerSlice {
			mSet := strings.Split(mixerItem, ":")
			if len(mSet) == 2 {
				k1 := mSet[0]
				v1 := mSet[1]
				valueMap := make(map[string]interface{})
				valueMap["SetVal"] = v1 // 设定值
				for _, c1Item := range consumptionDetail {
					if c1Item.Material == k1 {
						valueMap["ActVal"] = c1Item.ActualValue
					}
				}
				mList[k1] = valueMap
			}
		}
		dList["CONSUMPTION"] = mList
		dList["SCCJID"] = production.StationId
		dList["BH"] = production.TaskNo
		dList["DELIVERY_NO"] = production.DeliveryNo
		dList["PRODUCTION_QUANTITY"] = production.ProductionQuantity
		dList["LASTTIME"] = production.UpdatedAt
		productionSlice = append(productionSlice, dList)
	}

	response.Success(c, productionSlice)
}
